package com.ywk.base.dataStructure.stack;

import java.util.Scanner;

//数组模拟栈
public class ArrayStackDemo {

	public static void main(String[] args) {
		ArrayStack as=new ArrayStack(6);
		Scanner input=new Scanner(System.in);
		boolean loop=true; 
		char key;
		int date;
		while(loop) {
			System.out.println("s(show):显示栈");
			System.out.println("e(exit):退出程序");
			System.out.println("a(add):添加栈数据");
			System.out.println("g(get):取出栈顶数据");
			System.out.println("h(head):查看栈顶数据");
			System.out.print("请选择：");
			key=input.next().charAt(0);
			switch (key) {
			case 's':
				as.showStack();
				break;
			case 'e':
				input.close();
				loop=false;
				break;
			case 'a':
				System.out.println("请输入要加入的值：");
				date=input.nextInt();
				as.push(date);
				break;
			case 'g':
				try {
					System.out.println(as.pop());
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'h':
				as.showStackTop();
				break;
			default:
				break;
			}
		}
		as.push(10);
		as.push(20);
		as.push(30);
		as.showStack();
		System.out.println(as.pop());
		System.out.println(as.pop());

	}

}

class ArrayStack{
	private int maxSize;
	private int top=-1;
	private int[] stack;
	
	
	public ArrayStack(int maxSize) {
		super();
		this.maxSize = maxSize;
		stack=new int[this.maxSize];
	}
	//栈满条件
	public boolean isFull() {
		return top==maxSize-1;
	}
	//栈空条件
	public boolean isEmpty() {
		return top==-1;
	}
	//入栈
	public void push(int value) {
		if(isFull()) {
			System.out.println("栈满，请勿再添加");
			return;
		}
		top++;
		stack[top]=value;
	}
	//出栈
	public int pop() {
		if(isEmpty()) {
			throw new RuntimeException("栈空"); 
		}
		int value=stack[top];
		top--;
		return value;
	}
	
	public void showStack() {
		if(isEmpty()) {
			System.out.println("栈空");
		}
		for (int i = top; i >=0 ; i--) {
			System.out.printf("stack["+i+"]\n",stack[i]);
		}
	}
	
	public void showStackTop() {
		if(isEmpty()) {
			System.out.println("栈空");
		}
		System.out.println(stack[top]);
	}
}













